package gis.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.alibaba.fastjson.JSON;

import com.supermap.android.maps.CoordinateReferenceSystem;
import com.supermap.android.maps.LayerView;
import com.supermap.android.maps.LineOverlay;
import com.supermap.android.maps.MapView;
import com.supermap.android.maps.Overlay;
import com.supermap.android.maps.Point2D;
import com.supermap.android.maps.PolygonOverlay;
import com.supermap.android.maps.measure.MeasureResult;
import com.whu.zj.MyApplication;
import com.whu.zj.R;
import com.whu.zj.UIHandler;

import java.util.ArrayList;
import java.util.List;

import informationGet.activity.ShowImage;
import informationGet.dto.PointXY;
import informationGet.dto.Points;


/**
 * 地图显示模块
 */
public class MapShow extends UIHandler.BaseActivity {

    protected Bitmap bitmap_mark;
    public static  String DEFAULT_URL = "http://125.220.159.168:8090/iserver/services/map-HB/rest/maps/zjMap";
    static
    {
        String ip = MyApplication.share().getString(R.string.supermap_Ip);
        DEFAULT_URL = "http://"+ip+":8090/iserver/services/map-HB/rest/maps/zjMap";
    }
    protected MapView mapView;
    public LocationManager locationManager;
    public Location location;
    public static String filePath, filePathTmp, filePathBitmap, locationName;
    String localTempImgDir, localTempImgFileName, localTimeTemp;
    private final static int TAKE_PHOTO_WITH_DATA = 1;
    public Uri uri;
    private View m_DetailLayout;
    private PopupWindow pwDetailInfo;
    private TextView m_textLongitude, m_textLatitude, tv_positionValue;
    // 输入坐标查询
    private View m_DetailLayout_query;
    private PopupWindow pwDetailInfo_query;
    private TextView m_textfarmCode, m_textfarmDLMC, m_textfarmQSDWMC, m_textfarmZLDWMC;
    private TextView m_textfarmTBMJ, m_textfarmTBDLMJ, m_textfarmXZDWMJ, m_textfarmLXDWMJ;
    // 点击屏幕查询用水地信息
    private View m_AreaDetailLayout;
    private PopupWindow pwDetailInfo_area;
    private TextView m_textviewArea;
    public static double d_longitude, d_latitude;
    public final double offsetX = 18.599785, offsetY = 14.695709;//武汉经纬度与lake偏离量

    // 线面触屏Overlay，用来获取点坐标
    private TouchOverlay touchOverlay;
    // 显示量算结果的编辑文本控件
    private EditText text;
    // 存放绘制线或面的点集合
    private List<Point2D> geoPoints = new ArrayList<Point2D>();
    // 绘制要素状态
    private int drawStatic = -1;// 0代表绘制线，1表示绘制面
    // 默认的绘制面对象
    private PolygonOverlay polygonOverlay;
    // 默认的绘制线对象
    private LineOverlay lineOverlay;
    // 是否发生多点触碰
    public boolean isMultiTouch = false;
    // 清除标记
    Button btn_deleteoverlay;

    // 查看图片
    Button button_takephoto;

    // 传递进来的数据
    Points points = new Points();

    public Point2D locationPoint2D;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_show2);
        initMapShow();
        // 创建LocationManager对象
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        touchOverlay = new TouchOverlay();
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!network) {
            Dialog alertDialog = new AlertDialog.Builder(this).
                    setTitle("提高\"我的位置\"精确度").
                    setMessage("如需获取更精确的位置服务，请您在室内时执行以下操作:\n 打开WLAN").
                    setIcon(R.drawable.location_mark2).
                    setNeutralButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS );
                            Intent myIntent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                            startActivity(myIntent);
                        }
                    }).
                    setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                        }
                    }).
                    create();
            alertDialog.show();
            String str = "Network没有开!";
            Log.i("WLANmeiyuukai:", str);
        }

        // 定位
        Button btn_location = (Button) findViewById(R.id.button_location);
        btn_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestLocation();
            }
        });

        Button btn_collectLocation = (Button) findViewById(R.id.button_collectLocation);
        btn_collectLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        text = (EditText) this.findViewById(R.id.editText);
        Button btn_huiqu = (Button) findViewById(R.id.button_back);
        btn_huiqu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        // 显示图片
        button_takephoto = (Button) findViewById(R.id.button_takephoto);
        button_takephoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MapShow.this, ShowImage.class);
                intent.putExtra("points", points);
                MapShow.this.startActivity(intent);
            }
        });

    // 清除标记点图层
        btn_deleteoverlay = (Button) findViewById(R.id.button_deleteoverlay);
        btn_deleteoverlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mapView.removeOverlayByKey("locationOverlay");
            }
        });


        LayoutInflater lfCallOut_mearsure = getLayoutInflater();
        View m_DetailLayout_mearsure=lfCallOut_mearsure.inflate(R.layout.measure_menu, null);
        final PopupWindow pwDetailInfo_mearsure = new PopupWindow(m_DetailLayout_mearsure, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Button btn_measure=(Button) findViewById(R.id.button_mearsure);
        final boolean[] show = {true};
        btn_measure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //openOptionsMenu();
                if(show[0]){
                    pwDetailInfo_mearsure.showAtLocation(mapView, Gravity.NO_GRAVITY, 8, 50); // popwindow的显示位置
                    show[0] =false;
                }else{
                    pwDetailInfo_mearsure.dismiss();//popwindow消失
                    show[0] =true;
                }
            }
        });


        pwDetailInfo = new PopupWindow(m_DetailLayout, 250, 150);
        m_DetailLayout = View.inflate(this, R.layout.detailinfo, null);
        pwDetailInfo.setContentView(m_DetailLayout);
        m_textLongitude = (TextView) m_DetailLayout.findViewById(R.id.textview_longitude);
        m_textLatitude = (TextView) m_DetailLayout.findViewById(R.id.textview_latitude);
        tv_positionValue = (TextView) m_DetailLayout.findViewById(R.id.textview_farmQSDWMC);

        TextView m_textdistance=(TextView) m_DetailLayout_mearsure.findViewById(R.id.txt_distance);
        TextView m_textarea=(TextView)m_DetailLayout_mearsure.findViewById(R.id.txt_area);
        TextView m_textclear=(TextView)m_DetailLayout_mearsure.findViewById(R.id.txt_clear);

        lineOverlay = new LineOverlay(getLinePaint());
        mapView.getOverlays().add(lineOverlay);
        polygonOverlay = new PolygonOverlay(getPolygonPaint());
        mapView.getOverlays().add(polygonOverlay);

        m_textdistance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pwDetailInfo_mearsure.dismiss();//popwindow消失
                show[0] =true;
                showDiatanceMeasure();
            }
        });
        m_textarea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pwDetailInfo_mearsure.dismiss();//popwindow消失
                show[0] =true;
                showAreaMeasure();
            }
        });
        m_textclear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pwDetailInfo_mearsure.dismiss();//popwindow消失
                show[0] =true;
                clear();
            }
        });


        initdata();

    } //onCreate()结束

    public void showDiatanceMeasure() {
        clean();
        drawStatic = 0;
        // 添加LineOverlay绘线，地图刷新
        if (!mapView.getOverlays().contains(touchOverlay)) {
            mapView.getOverlays().add(touchOverlay);
        }
        mapView.invalidate();
    }

    /**
     * <p>
     * 展示面积量算
     * </p>
     */
    public void showAreaMeasure() {
        clean();
        drawStatic = 1;
        // 添加PolygonOverlay绘面，地图刷新
        if (!mapView.getOverlays().contains(touchOverlay)) {
            mapView.getOverlays().add(touchOverlay);
        }
        mapView.invalidate();
    }

    // 绘面风格
    private Paint getPolygonPaint() {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.BLUE);
        paint.setAlpha(50);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeWidth(2);
        return paint;
    }

    // 绘线风格
    private Paint getLinePaint() {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.BLUE);
        paint.setAlpha(50);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(5);
        return paint;
    }

    // 清除
    public void clear() {
        if (mapView.getOverlays().contains(touchOverlay)) {
            mapView.getOverlays().remove(touchOverlay);
        }
        drawStatic = -1;
        clean();
        text.setVisibility(View.INVISIBLE);
        mapView.invalidate();
    }

    private void clean() {
        lineOverlay.setData(new ArrayList<Point2D>());
        polygonOverlay.setData(new ArrayList<Point2D>());
        geoPoints.clear();
        text.setText("");
    }

    // 请求位置
    private void requestLocation() {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 1, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                updateLocation(location);
                drawOnMap();
                locationManager.removeUpdates(this);
            }

            @Override
            public void onProviderDisabled(String provider) {
                updateLocation(null);
            }

            @Override
            public void onProviderEnabled(String provider) {
                // 当GPS LocationProvider可用时，更新位置
                updateLocation(locationManager.getLastKnownLocation(provider));
            }

            @Override
            public void onStatusChanged(String provider, int status,
                                        Bundle extras) {
            }
        });
    }


    // 获取到坐标后，绘图
    private void drawOnMap() {
        if (location != null) {
            Point2D point2D2 = new Point2D(location.getLongitude() + offsetX, location.getLatitude() + offsetY);
            setPoint2DOnMap(point2D2);
        } else {
        }
    }

    // 地图上标记定位点
    protected void setPoint2DOnMap(Point2D point2D) {
        // 定位到指定点

        //Drawable bitmap_mark = getResources().getDrawable(R.mipmap.min_blue_pin);
        //Point2D point2D = new Point2D(132 + 51.0 / 60 + 49.46 / 3600, 45 + 21.0 / 60 + 20.97 / 3600);
        setLocationPoint2D(point2D);
        MyOwnOverlay myOwnOverlay = new MyOwnOverlay();
        myOwnOverlay.setKey("locationOverlay");//设置瓦片的key，便于删除
        mapView.getOverlays().add(myOwnOverlay);
        mapView.invalidate();//添加瓦片之后，及时刷新图层
    }

    // 更新坐标
    public void updateLocation(Location newLocation) {
        location = newLocation;
        d_longitude = newLocation.getLongitude();
        d_latitude = newLocation.getLatitude();
    }

    public void setLocationPoint2D(Point2D point2D) {
        locationPoint2D = point2D;
    }

    public Point2D getLocationPoint2D() {
        return locationPoint2D;
    }

    public Point2D getLocation() {
        Point2D point2D = new Point2D(location.getLongitude(), location.getLatitude());
        return point2D;
    }

    //初始界面显示地图
    public void initMapShow() {
        mapView = (MapView) this.findViewById(R.id.mapview);
        LayerView layerView = new LayerView(this);
        layerView.setURL(DEFAULT_URL);
        CoordinateReferenceSystem crs = new CoordinateReferenceSystem();
        crs.wkid = 4326;
        layerView.setCRS(crs);
        //设置比例尺数组
        mapView.fixedLevelsEnabled = true;
//        double scales[] = {1.0 / 681710.44500652316, 1.0 / 166434.19191046193, 1 / 11437.270579065907};
        double scales[] = {1/288895.855,1/144449.59999999997 ,1/72225.000000000073, 1/36119.999999999964, 1/18060.000000000015, 1/9028.0000000000127,1/4514.000000000006,1/2257.000000000003};
        layerView.setScales(scales);
        mapView.setClickable(true);
        mapView.setBuiltInZoomControls(true);
        mapView.addLayer(layerView);
        mapView.invalidate();//刷新地图
    }

    // 初始化数据
    private void initdata() {
//        if (getIntent().getSerializableExtra("points") != null) {
//            points = (Points) getIntent().getSerializableExtra("points");
//            String locations = points.getLocations();
//            List<PointXY> pointXies = JSON.parseArray(locations, PointXY.class);
//            for (PointXY pointXY : pointXies) {
////                drawLocationOnMap(new Point2D(pointXY.getX(),pointXY.getY()));
//            }
//
//            button_takephoto.setVisibility(View.VISIBLE);
//        }
    }

    class MyOwnOverlay extends Overlay {
        Point2D point2D = getLocationPoint2D();
        Paint paint = new Paint();

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {
            // 在目标点的位置绘制
            Point point = mapView.getProjection().toPixels(point2D, null);
            bitmap_mark = BitmapFactory.decodeResource(getResources(), R.drawable.min_blue_pin);
            canvas.drawBitmap(bitmap_mark, point.x - bitmap_mark.getWidth() / 2, point.y - bitmap_mark.getHeight() / 2, paint);
            //canvas.drawText("★这里是定位点", point.x, point.y, paint);
        }

        @Override
        public boolean onTap(Point2D point2D, MapView mapView) {
            Point2D point2D_show = new Point2D(getLocation());
            m_textLongitude.setText(Double.toString(point2D_show.getX() + offsetX));
            m_textLatitude.setText(Double.toString(point2D_show.getY() + offsetY));
            tv_positionValue.setText("待完成");
            pwDetailInfo.showAtLocation(mapView, Gravity.NO_GRAVITY, 8, 50); // popwindow的显示位置


            m_DetailLayout.findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    pwDetailInfo.dismiss();
                }
            });
            return true;
        }

    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.destroy();
    }


    class TouchOverlay extends Overlay {
        // 触屏的x坐标
        private int touchX;
        // 触屏的y坐标
        private int touchY;
        private List<Point> movePoints = new ArrayList<Point>();

        @Override
        public boolean onTouchEvent(MotionEvent event, final MapView mapView) {
            if (event.getPointerCount() > 1) {// 发生多点触碰
                isMultiTouch = true;
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (movePoints.size() > 1) {// 如果发生平移，不绘制
                    double distance = 0;
                    for (int i = movePoints.size() - 1; i > 0; i--) {
                        double ds = Math.pow((movePoints.get(i).x - movePoints.get(i - 1).x), 2) + Math.pow((movePoints.get(i).y - movePoints.get(i - 1).y), 2);
                        if (ds > distance) {
                            distance = ds;
                        }
                    }
                    if (distance > 16) {
                        return false;
                    }
                }
                if (isMultiTouch) {// 如果发生多点触碰，不绘制
                    isMultiTouch = false;
                    return false;
                }
                text.setVisibility(View.VISIBLE);
                text.setTextSize(10);
                text.setText("");
                touchX = Math.round(event.getX());
                touchY = Math.round(event.getY());
                // 记录点击位置
                Point2D touchGeoPoint = mapView.getProjection().fromPixels(touchX, touchY);
                geoPoints.add(touchGeoPoint);
                if (drawStatic == 0) {
                    setOverlayData(lineOverlay);
                    if (geoPoints.size() >= 2) {
                        com.supermap.services.components.commontypes.Point2D[] pts = changePiont2D(geoPoints);
                        MeasureResult result = MeasureUtil.distanceMeasure(DEFAULT_URL, pts);
                        if (result != null) {
                            text.setText("量算结果：" + result.distance + "米");
                            Log.d("MeasureDemo", "量算结果" + text);
                        }
                    }

                } else if (drawStatic == 1) {
                    setOverlayData(polygonOverlay);
                    if (geoPoints.size() >= 3) {
                        com.supermap.services.components.commontypes.Point2D[] pts = changePiont2D(geoPoints);
                        MeasureResult result = MeasureUtil.areaMeasure(DEFAULT_URL, pts);
                        if (result != null) {
                            text.setText("量算结果：" + result.area + "平方千米");
                            Log.d("MeasureDemo", "量算结果" + text);
                        }
                    }
                }
            } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
                movePoints.clear();
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                movePoints.add(new Point(Math.round(event.getX()), Math.round(event.getY())));
            }
            return false;
        }

        /**
         * 给Overlay设置点集合，开始绘制对象，并刷新地图
         *
         * @param overlay
         * @param gps
         */
        private void setOverlayData(Overlay overlay, List<Point2D> gps) {
            if (overlay == null) {
                return;
            }
            List<Point2D> geoPointList = new ArrayList<Point2D>();
            if (gps != null && gps.size() > 0) {
                copyList(gps, geoPointList);
            } else if (geoPoints.size() > 0) {
                copyList(geoPoints, geoPointList);
            }
            if (geoPointList.size() > 0) {
                if (overlay instanceof LineOverlay) {
                    ((LineOverlay) overlay).setData(geoPointList);

                } else if (overlay instanceof PolygonOverlay) {
                    ((PolygonOverlay) overlay).setData(geoPointList);
                }
                mapView.invalidate();
            }
        }

        private void copyList(List<Point2D> sourcegps, List<Point2D> targetgps) {
            for (int i = 0; i < sourcegps.size(); i++) {
                targetgps.add(new Point2D(sourcegps.get(i)));
            }
        }

        private void setOverlayData(Overlay overlay) {
            setOverlayData(overlay, null);
        }

        private com.supermap.services.components.commontypes.Point2D[] changePiont2D(List<Point2D> gps) {
            com.supermap.services.components.commontypes.Point2D[] pts = new com.supermap.services.components.commontypes.Point2D[gps.size()];
            for (int j = 0; j < gps.size(); j++) {
                pts[j] = new com.supermap.services.components.commontypes.Point2D(gps.get(j).x, gps.get(j).y);
            }
            return pts;
        }
    }
}

